package com.tanhua.autoconfig.template;

import com.tanhua.autoconfig.properties.SmsProperties;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

public class SmsTemplate {


    private RestTemplate restTemplate;

    private SmsProperties properties;

    private static String Url = "http://106.ihuyi.com/webservice/sms.php?method=Submit";



    public SmsTemplate(SmsProperties properties,RestTemplate restTemplate) {
        this.properties = properties;
        this.restTemplate=restTemplate;
    }

    public void sendSms(String mobile,String code) {

//        try {
//            //配置阿里云
//            Config config = new Config()
//                    // 您的AccessKey ID
//                    .setAccessKeyId(properties.getAccessKey())
//                    // 您的AccessKey Secret
//                    .setAccessKeySecret(properties.getSecret());
//            // 访问的域名
//            config.endpoint = "http://106.ihuyi.com/webservice/sms.php?method=Submit";
//
//            com.aliyun.dysmsapi20170525.Client client =  new com.aliyun.dysmsapi20170525.Client(config);
//
//            SendSmsRequest sendSmsRequest = new SendSmsRequest()
//                    .setPhoneNumbers(mobile)
//                    .setSignName(properties.getSignName())
//                    .setTemplateCode(properties.getTemplateCode())
//                    .setTemplateParam("{\"code\":\""+code+"\"}");
//            // 复制代码运行请自行打印 API 的返回值
//            SendSmsResponse response = client.sendSms(sendSmsRequest);
//
//            SendSmsResponseBody body = response.getBody();
//
//            System.out.println(body.getMessage());
//
//        }catch (Exception e) {
//            e.printStackTrace();
//        }
        HttpHeaders headers = new HttpHeaders();
        MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
        map.add("account", properties.getAccessKey());
        map.add("password",properties.getSecret());
        map.add("mobile", mobile);
        map.add("content", "您的验证码是：" + code + "。请不要把验证码泄露给其他人。");
        map.add("format", "json");

        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(map, headers);
        Map<String, Object> result = null;

        result= restTemplate.postForObject(Url, request, Map.class);
        if (result.getOrDefault("code", "0").toString().equals("2")) {
            System.out.print("成功");
        } else {
            System.out.print("失败");
         }


    }

}
